import axios, { type AxiosInstance } from 'axios'
import type { RequestConfig, RequestInterceptors } from './types'

class Request {
  instance: AxiosInstance
  interceptors?: RequestInterceptors

  constructor(config: RequestConfig) {
    this.instance = axios.create(config)
    //获取与处理实例初始化时传递的拦截器
    this.interceptors = config.interceptors
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch,
    )
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch,
    )
    //添加所有实例都有的拦截器
    //request 后定义先执行
    //response 先定义先执行
    this.instance.interceptors.request.use(
      (config) => {
        return config
      },
      (err) => {
        return err
      },
    )
    this.instance.interceptors.response.use(
      (res) => {
        return res
      },
      (err) => {
        return err
      },
    )
  }

  request<T>(config: RequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      if (config.interceptors?.requestInterceptor) {
        this.instance.interceptors.request.use(
          config.interceptors?.requestInterceptor,
          config.interceptors?.requestInterceptorCatch,
        )
        this.instance.interceptors.response.use(
          config.interceptors?.responseInterceptor,
          config.interceptors?.responseInterceptorCatch,
        )
      }
      this.instance
        .request<unknown, T>(config)
        .then((res) => {
          resolve(res)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  get<T>(config: RequestConfig): Promise<T> {
    return this.request({ ...config, method: 'GET' })
  }
  post<T>(config: RequestConfig): Promise<T> {
    return this.request({ ...config, method: 'POST' })
  }
  delete<T>(config: RequestConfig): Promise<T> {
    return this.request({ ...config, method: 'DELETE' })
  }
  patch<T>(config: RequestConfig): Promise<T> {
    return this.request({ ...config, method: 'PATCH' })
  }
  put<T>(config: RequestConfig): Promise<T> {
    return this.request({ ...config, method: 'PUT' })
  }
}

export default Request
